<template>
  <div class="container">
    <n-drawer v-model:show="isDrawer" :width="width">
      <n-drawer-content :title="title" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
        >
          <n-form-item label="标题" path="title">
            <n-input placeholder="请输入标题" v-model:value="formParams.title" />
          </n-form-item>
          <n-form-item label="标签" path="tags">
            <n-dynamic-tags v-model:value="formParams.tags" type="info" />
          </n-form-item>
          <n-form-item label="用户名" path="tags" style="width: 300px">
            <n-select
              v-model:value="formParams.userId"
              :options="userOptions"
              label-field="username"
              value-field="userId"
              filterable
            />
          </n-form-item>
          <n-form-item label="分类" path="categoryId" style="width: 300px">
            <n-tree-select
              v-model:value="formParams.categoryId"
              :options="categoryOptions"
              label-field="label"
              value-field="id"
              key-field="id"
              children-field="children"
              filterable
            />
          </n-form-item>
          <n-form-item label="预览图" path="preview">
            <n-upload
              action="/upload"
              @finish="uploadSuccess"
              :max="1"
              list-type="image-card"
              :default-file-list="previewFileList"
            />
          </n-form-item>
          <div class="flex">
            <div class="flex-1 editor">
              <XingzhuEditor @get-html="htmlValue" />
            </div>
          </div>
        </n-form>

        <template #footer>
          <n-space>
            <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, onMounted } from 'vue';
  import { UploadFileInfo, useMessage } from 'naive-ui';
  import { getMaterialCategory } from '@/api/material/materialCategory';
  import { insertMaterial } from '@/api/material/material';
  import { getAllUser } from '@/api/system/user';
  import XingzhuEditor from '@/components/XingZhuEditor/index.vue';

  const props = defineProps({
    title: {
      type: String,
      default: '添加素材分类',
    },
    width: {
      type: Number,
      default: 450,
    },
    reloadTable: { type: Function, default: () => {} },
  });
  defineExpose({
    openDrawer,
  });

  const previewFileList = ref<UploadFileInfo[]>([
    {
      id: 'xingzhu',
      name: 'xingzhu_' + new Date().getTime(),
      status: 'finished',
      url: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg',
    },
  ]);

  const rules = {
    label: {
      required: true,
      message: '请输入标题',
      trigger: 'blur',
    },
    path: {
      required: true,
      message: '请输入路径',
      trigger: 'blur',
    },
  };

  let isDrawer = ref(false);
  let subLoading = ref(false);
  let formParams = reactive({
    title: '',
    preview: [''],
    state: 1,
    details: '',
    userId: 1,
    categoryId: 1,
    tags: [],
    id: 0,
  });

  const htmlValue = (value) => {
    console.log(value);
    formParams.details = value;
  };
  const categoryOptions = ref();
  const userOptions = ref();
  onMounted(async () => {
    const treeMenuList = await getMaterialCategory();
    categoryOptions.value = treeMenuList;
    const userList = await getAllUser();
    userOptions.value = userList;
  });
  const message = useMessage();
  const formRef: any = ref(null);
  const defaultValueRef = () => ({
    title: '',
    preview: [''],
    details: '',
    userId: 1,
    categoryId: 1,
    tags: [],
  });

  const uploadSuccess = ({ file, event }: { file: UploadFileInfo; event?: ProgressEvent }) => {
    console.log(event);

    const res = JSON.parse((event?.target as XMLHttpRequest).response);
    if (res.code === 200) {
      console.log(res.result);
      formParams.preview[0] = res.result;
      previewFileList.value[0].url = formParams.preview[0];
      console.log(previewFileList.value[0].url);
      message.success('图片上传成功');
    } else {
      message.error('图片上传失败');
    }
    return file;
  };

  function openDrawer() {
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  const formSubmit = () => {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        let { tags, title, details, userId, categoryId, preview } = formParams;
        let tagsStr = tags.join(' ');
        let material = {
          title,
          details,
          userId,
          categoryId,
          tags: tagsStr,
          preview: preview[0],
        };
        console.log(material);

        await insertMaterial(material);
        message.success('添加成功');
        props.reloadTable();

        handleReset();
        closeDrawer();
      } else {
        message.error('请填写完整信息');
      }
    });
  };

  function handleReset() {
    formRef.value.restoreValidation();
    formParams = Object.assign(formParams, defaultValueRef());
  }
</script>

<style lang="less">
  .ql-toolbar.ql-snow {
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: 1px solid #eee;
  }
  .editor {
    padding: 10px;
    border: 1px solid #eee;
  }
  .show {
    border: 1px solid #eee;
    padding: 10px;
  }

  .ql-container.ql-snow {
    border: none;
  }
</style>
<style scoped>
  .avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
  }
</style>
